<template>
  <base-breadcrumb>
    <a-card v-loading="loading">
      <title-name>{{ sourceData.categoryName }}</title-name>
      <span style="color: red">备注：根据总分计算配置的规则计算后， 管理行为与现场管理得分之和必须等于100分。</span>
      <div class="wrapper">
        <div class="left">
          <div class="nav" @click="activeKey = 0" :class="{active:activeKey === 0}">
            管理行为({{ sourceData.checkRecordMarkSheetDTOS[0].checkScore }}分)
          </div>
          <div class="nav" @click="activeKey = 1" :class="{active:activeKey === 1}">
            现场管理得分({{ sourceData.checkRecordMarkSheetDTOS[1].checkScore }}分)
          </div>
          <div class="nav" @click="activeKey = 2" :class="{active:activeKey === 2}">
            减分项({{ sourceData.checkRecordMarkSheetDTOS[2].checkScore }}分)
          </div>
        </div>
        <div class="right">
          <div style="display:flex;justify-content: space-between;margin-bottom: 20px;">
            <a-button type="primary" @click="visible = true">添加考核内容</a-button>
            <a @click="visible2 = true">总分计算配置</a>
          </div>
          <b-table
            bordered
            :show-page="false"
            ref="table"
            :columns="columns"
            :request="loadData"
          >
            <template slot="operation" slot-scope="text, record">
              <div class="pub-table-list-action">
                <span @click="form = $clone(record);visible = true">编辑</span>
                <span @click="del(record)">删除</span>
              </div>
            </template>
            <template slot="html1" slot-scope="text, record">
              <pre
                style="white-space: pre-wrap;font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol';"
              >{{ text }}
              </pre>
            </template>
          </b-table>
        </div>
      </div>
    </a-card>
     <div class="page-btn-right-top">
        <a-button type="primary" @click="save">保存</a-button>
      </div>

    <a-modal
      :visible="visible"
      title="考核内容"
      @cancel="cancel"
      @ok="add"
      okText="添加"
    >
      <div style="padding-left: 20px;color: black;margin-bottom: 10px;">
        <div v-if="activeKey === 0">管理行为</div>
        <div v-if="activeKey === 1">现场管理得分</div>
        <div v-if="activeKey === 2">加分项</div>
      </div>
      <div class="about-master-container">
        <BForm ref="bform" :form="form" :config="formConfig" :rule="rule" />
      </div>
    </a-modal>

    <totalScoreCalcModal :visible.sync="visible2"
                         :sourceData="sourceData"
                         @ok="mergeList"
    />

  </base-breadcrumb>
</template>
<script>
import totalScoreCalcModal from './totalScoreCalcModal'
import Api from '@/api/safetySupervision/base/checkLogScore.js'

export default {
  name: 'projectManageCheck',
  components: {
    totalScoreCalcModal
  },
  props: {},
  data() {
    return {
      form: {},
      visible: false,
      visible2: false,
      loading: false,
      columns: [
        { title: '考核内容', dataIndex: 'assessmentContent', width: 150 },
        { title: '考核细则', dataIndex: 'assessmentRules', width: 500, scopedSlots: { customRender: 'html1' } },
        { title: '得分标准', dataIndex: 'scoreCriteria', scopedSlots: { customRender: 'html1' } },
        { title: '得分', dataIndex: 'score', width: 100 },
        { title: '排序', dataIndex: 'sorted', width: 100 },
        {
          title: '操作',
          width: 120,
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      activeKey: 0,
      loadData: () => {
        return { code: 200, data: this.tableData }
      },
      sourceData: {
        id: Date.now() + 4,
        categoryName: '加分项',
        checkRecordMarkSheetDTOS: [
          {
            accounted: 100,
            checkName: '管理行为',
            checkScore: 120,
            sorted: 1,
            checkRecordMarkSheetDetailsDTOS: []
          },
          {
            accounted: 100,
            checkName: '现场管理得分',
            checkScore: 120,
            sorted: 1,
            checkRecordMarkSheetDetailsDTOS: []
          },
          {
            accounted: 100,
            checkName: '加分项',
            checkScore: 120,
            sorted: 1,
            checkRecordMarkSheetDetailsDTOS: []
          }
        ]
      },
      rule: {
        assessmentContent: [{ required: true, message: '请输入', trigger: 'blur' }],
        assessmentRules: [{ required: true, message: '请输入', trigger: 'blur' }],
        scoreCriteria: [{ required: true, message: '请输入', trigger: 'blur' }],
        score: [{ required: true, message: '请输入', trigger: 'blur' }],
        sorted: [{ required: true, message: '请输入', trigger: 'blur' }]
      }
    }
  },
  computed: {
    formConfig() {
      return [
        {
          row: true,
          children: [
            { type: 'input', value: 'assessmentContent', label: '考核内容', colSpan: 24 },
            { type: 'textarea', value: 'assessmentRules', label: '考核细则', colSpan: 24, noFixed: true },
            { type: 'textarea', value: 'scoreCriteria', label: '得分标准', colSpan: 24, noFixed: true },
            { type: 'number', value: 'score', label: '得分', colSpan: 24, attrs: { min: 0, max: 50000 } },
            { type: 'number', value: 'sorted', label: '排序', colSpan: 24, attrs: { min: 0, max: 1000, isInt: true } }
          ]
        }
      ]
    },
    tableData: {
      get() {
        return this.sourceData.checkRecordMarkSheetDTOS[this.activeKey].checkRecordMarkSheetDetailsDTOS
      },
      set(val) {
        this.sourceData.checkRecordMarkSheetDTOS[this.activeKey].checkRecordMarkSheetDetailsDTOS = val
      }
    }
  },
  watch: {
    activeKey(newVal) {
      this.$refs.table.refresh()
    }
  },
  created() {
    if (this.$route.query.id) {
      this.sourceData.id = this.$route.query.id
      this.getData()
    }
  },
  methods: {
    mergeList(data) {
      this.sourceData.checkRecordMarkSheetDTOS.map((v, i) => {
        v.accounted = data.checkRecordMarkSheetDTOS[i].accounted
      })
    },
    del(row) {
      this.$submitConfirm(() => {
        let resIndex = this.tableData.findIndex(v => v.id === row.id)
        if (resIndex !== -1) {
          this.tableData.splice(resIndex, 1)
          this.$refs.table.refresh()
          this.calcScore()
        }
      }, '确认删除？')
    },
    add() {
      this.$refs.bform.validate(valid => {
        if (valid) {
          if (this.form.id) {
            let resIndex = this.tableData.findIndex(v => v.id === this.form.id)
            if (resIndex !== -1) {
              this.tableData[resIndex] = this.$clone(this.form)
            }
          } else {
            let temp = this.$clone(this.form)
            temp.id = Date.now()
            this.tableData.push(temp)
          }

          this.calcScore()
          this.$refs.table.refresh()
          this.visible = false
          this.form = {}
        }
      })
    },
    calcScore() {
      let total = this.tableData.reduce((acc, cur, index) => {
        acc += cur.score
        return acc
      }, 0)
      console.log(total)
      this.sourceData.checkRecordMarkSheetDTOS[this.activeKey].checkScore = total
    },
    cancel() {
      this.form = {}
      this.$refs.bform.clearValidate()
      this.visible = false
    },
    async getData() {
      this.loading = true
      let res = await Api.findById({ id: this.sourceData.id })
      this.loading = false
      if (res.code === this.SUCCESS_CODE) {
        this.sourceData = res.data
        this.sourceData.checkRecordMarkSheetDTOS.map(v => {
          if (!v.checkRecordMarkSheetDetailsDTOS) {
            v.checkRecordMarkSheetDetailsDTOS = []
          } else {
            v.checkRecordMarkSheetDetailsDTOS.map(w => w.id = (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1))
          }
        })
        this.calcScore()
        this.$refs.table.refresh()
      }
    },
    async save() {
      let row1 = this.sourceData.checkRecordMarkSheetDTOS[0]
      let row2 = this.sourceData.checkRecordMarkSheetDTOS[1]
      if (((row1.accounted / 100) * row1.checkScore + (row2.accounted / 100) * row2.checkScore) !== 100) {
        return this.$noticeWarning('管理行为与现场管理得分 计算后的分值之和不等于100分')
      }
      let temp = this.$clone(this.sourceData)
      temp.checkRecordMarkSheetDTOS.map(v => {
        v.checkRecordMarkSheetDetailsDTOS.map(w => {
          delete w.id
        })
      })

      this.loading = true
      let res = await Api.editByMain({}, temp)
      this.loading = false
      if (res.code === this.SUCCESS_CODE) {
        this.$noticeSuccess('保存成功')
        this.$close()
      }
    }
  }
}
</script>
<style lang="less" scoped>
.wrapper {
  margin-top: 20px;
  display: flex;

  .left {
    max-height: 162px;
    //width: 100px;
    border: 1px solid #d9d9d9;

    .nav {
      height: 40px;
      width: 140px;
      display: flex;
      align-items: center;
      //justify-content: center;
      border-top: 1px solid #d9d9d9;

      &:nth-child(1) {
        border: none;
      }

      &.active {
        background: rgb(2, 167, 240);
        color: white;
      }
    }
  }

  .right {
    flex: 1;
    margin-left: 15px;
  }
}

</style>
